"use client";
import { useState, useEffect } from "react";
import { Button, Dropdown, Avatar, message, Modal } from "antd";
import { UserOutlined, LogoutOutlined } from "@ant-design/icons";
import type { MenuProps } from "antd";
import { useRouter } from "next/navigation";

interface UserData {
  id: number;
  mobile: string;
  token: string;
}

export default function UserInfo() {
  const [userInfo, setUserInfo] = useState<UserData | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  useEffect(() => {
    // 从localStorage获取用户信息
    const loadUserInfo = () => {
      const storedUserInfo = localStorage.getItem("userInfo");
      if (storedUserInfo) {
        try {
          const userData = JSON.parse(storedUserInfo);
          setUserInfo(userData);
        } catch (error) {
          console.error("解析用户信息失败:", error);
          localStorage.removeItem("userInfo");
          localStorage.removeItem("token");
          setUserInfo(null);
        }
      } else {
        setUserInfo(null);
      }
      setLoading(false);
    };

    // 初始加载
    loadUserInfo();

    // 监听localStorage变化
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "userInfo") {
        loadUserInfo();
      }
    };

    // 监听自定义事件（用于同页面内的状态同步）
    const handleUserInfoChange = () => {
      loadUserInfo();
    };

    window.addEventListener("storage", handleStorageChange);
    window.addEventListener("userInfoChanged", handleUserInfoChange);

    return () => {
      window.removeEventListener("storage", handleStorageChange);
      window.removeEventListener("userInfoChanged", handleUserInfoChange);
    };
  }, []);

  // 登出处理
  const handleLogout = () => {
    Modal.confirm({
      title: "确认退出",
      content: "您确定要退出登录吗？",
      okText: "确定",
      cancelText: "取消",
      onOk() {
        localStorage.removeItem("userInfo");
        localStorage.removeItem("token");
        setUserInfo(null);

        // 触发自定义事件，通知其他组件用户信息已更新
        window.dispatchEvent(new CustomEvent("userInfoChanged"));

        message.success("已退出登录");
        router.push("/");
      },
    });
  };

  // 下拉菜单项
  const menuItems: MenuProps["items"] = [
    // {
    //   key: "profile",
    //   icon: <UserOutlined />,
    //   label: "个人中心",
    //   onClick: () => {
    //     // TODO: 跳转到个人中心页面
    //     message.info("个人中心功能开发中...");
    //   },
    // },
    // {
    //   key: "settings",
    //   icon: <SettingOutlined />,
    //   label: "设置",
    //   onClick: () => {
    //     // TODO: 跳转到设置页面
    //     message.info("设置功能开发中...");
    //   },
    // },
    {
      type: "divider",
    },
    {
      key: "logout",
      icon: <LogoutOutlined />,
      label: "退出登录",
      onClick: handleLogout,
    },
  ];

  // 如果正在加载，显示加载状态
  if (loading) {
    return (
      <div className="flex items-center">
        <div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse"></div>
      </div>
    );
  }

  // 如果未登录，显示登录按钮
  if (!userInfo) {
    return (
      <Button
        type="link"
        href="/login"
        className="text-gray-700 hover:text-blue-600 transition-colors px-3 py-1 rounded hover:bg-blue-50"
      >
        登录/注册
      </Button>
    );
  }

  // 如果已登录，显示用户信息下拉菜单
  return (
    <Dropdown
      menu={{ items: menuItems }}
      placement="bottomRight"
      trigger={["click"]}
    >
      <div className="flex items-center cursor-pointer hover:bg-gray-50 rounded-lg px-3 py-2 transition-colors">
        <Avatar
          size="small"
          className="shadow-md border-2 border-white"
          style={{
            fontSize: "14px",
            fontWeight: "bold",
            color: "white",
            background: "linear-gradient(135deg, #ec4899, #8b5cf6, #4f46e5)",
          }}
        >
          {userInfo.mobile.charAt(0)}
        </Avatar>
        <span className="ml-2 text-sm text-gray-700 font-medium">
          {userInfo.mobile.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")}
        </span>
      </div>
    </Dropdown>
  );
}
